package com.citywithincity.utils;

import java.io.File;
import java.io.IOException;

public class UploadUtil {
	/**
	 * 根目录
	 */
	private static String rootPath;
	private static String uploadContext;
	static{
		//rootpath 一定是带一个/
		rootPath  = ConfigReader.getDefault().get("upload_path");
		if(StringUtils.isEmpty(rootPath)){
			//默认网站
			rootPath = PathUtil.getRealPath("");
			
		}else{
			if(!rootPath.endsWith("/")){
				rootPath = rootPath+"/";
			}
		}
		
		//上传前缀
		uploadContext = ConfigReader.getDefault().get("upload_context");
		if(!uploadContext.endsWith("/")){
			uploadContext = uploadContext+"/";
		}
	}
	

	/**
	 * 获取上传文件名
	 * @param ext  扩展名称，不包含.
	 * @return
	 */
	private static String getUploadFile(String ext){
		StringBuilder sb = new StringBuilder(60);
		sb.append(DateTimeUtil.today()).append('/');
		StringBuilder dir = new StringBuilder(rootPath).append(sb);
		File file = new File(dir.toString());
		if(!file.exists()){
			file.mkdirs();
		}
		sb.append(MD5Util.md5Appkey(String.valueOf(System.nanoTime() * Math.random())))
		.append('.').append(ext);
		
		return sb.toString();
	}
	
	public static UploadFileInfo doUpdate(String ext,byte[] bytes) throws IOException{
		UploadFileInfo fileInfo = getUploadFileInfo(ext);
		IoUtil.write(fileInfo.getFile(), bytes);
		return fileInfo;
	}
	
	
	public static File getUploadPath(){
		StringBuilder dir = new StringBuilder(rootPath).append(DateTimeUtil.today()).append('/');
		File file = new File(dir.toString());
		if(!file.exists()){
			file.mkdirs();
		}
		return file;
	}
	
	
	/**
	 * 获取上传文件信息
	 * @param ext 后缀，不需要"."
	 * @return
	 */
	public static UploadFileInfo getUploadFileInfo(String ext){
		File file = null;
		String path = null;
		while(true){
			path = UploadUtil.getUploadFile(ext);
			file = new File(rootPath+path);
			if(!file.exists()){
				break;
			}
		}
		
		return new UploadFileInfo(file,path, uploadContext+path);
	}
	
	
	

	
}
